package com.ebt.m.customer.task;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.text.TextUtils;
import android.util.Log;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerContact;
import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.item.Contact;
import com.ebt.m.customer.item.Contact.CommonContact;
import com.ebt.m.customer.net.json.CustomerCRUDRetJson;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.CustomerData;
import com.ebt.m.data.DatabaseManager;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.utils.JsonUtil;
import com.ebt.m.widget.MaterialishProgressDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * 此类的主要作用是：
 * 1.通过在import界面，获取到的customerUUid<-->Contact键值对数据，将contact的相关数据存储到customer_contact表中
 *
 * @author Rick.Wang
 */
public class ImportOtherContactInfoTask implements Runnable {

    private static final String TAG = "tag";
    public static final int TASK_STATE_IDLE = 0;
    public static final int TASK_STATE_RUNNING = 1;
    public static final int TASK_STATE_DONE = 2;
    public static final int TASK_STATE_FAIL = 3;

    private int taskState = TASK_STATE_IDLE;

    private Context context;
    private ArrayList<Contact> contactsWithCUuid;

    public void setContext(Context context) {
        this.context = context;
    }

    private static ImportOtherContactInfoTask instance;

    private ImportOtherContactInfoTask() {
    }

    public static ImportOtherContactInfoTask getInstance() {

        if (instance == null) {
            synchronized (ImportOtherContactInfoTask.class) {
                if (instance == null) {
                    instance = new ImportOtherContactInfoTask();
                }
            }
        }
        return instance;
    }

    @Override
    public void run() {
        taskState = TASK_STATE_RUNNING;
        if (contactsWithCUuid == null) {
            taskState = TASK_STATE_DONE;
            throw new IllegalArgumentException("given ArrayList<Contact> contactsWithCUuid which should not be null ");
        }

        addContactsOtherInfo(this.context, contactsWithCUuid);
        taskState = TASK_STATE_DONE;
    }

    private void addContactsOtherInfo(Context context, ArrayList<Contact> contacts) {

        DatabaseManager dbManager = DatabaseManager.getInstance(context);
        dbManager.open();
        SQLiteDatabase db = dbManager.getSqliteDatabase();

        List<CustomerDetail> customerDetails = new ArrayList<>();
        Date birthdayD = DateUtils.getDefaultCustomerBirthday();
        long birthdayL = DateUtils.convertTimestampFromMilliToSecond(birthdayD.getTime());

        for (Contact contact : contacts) {
            CustomerDetail cd = new CustomerDetail();
            cd.setName(contact.name);
            if (!TextUtils.isEmpty(contact.name) && contact.name.length() > 0) {
                cd.setNamePrefix(String.valueOf(contact.name.charAt(0)));
            }
            cd.setMarriage(0);
            cd.setBirthday(birthdayL);
            cd.setIsConfirm(0);
            cd.setSex(1);
            cd.setRelationFlag(1);
            cd.setImportContact(contact.remarkUuid);//特征值
            cd.setCareerCategory(CustomerConstant.CareerCategory.CAREER_CATEGORY_1);

            String phone = null;
            String email = null;

            String name_raw_contact_id = contact.getRawContactId();

            //获取联系人号码
            Cursor cursorPhones = context.getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[]{
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            ContactsContract.CommonDataKinds.Phone.TYPE
                    },
                    ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID
                            + " = " + name_raw_contact_id, null, null);

            if (cursorPhones != null) {
                if (cursorPhones.moveToFirst()) {
                    do {
                        // 遍历所有的电话号码
                        String phoneNumber = cursorPhones.getString(0);
                        String phoneClassification = cursorPhones.getString(1);
                        String phoneDescription = null;
                        if (TextUtils.isEmpty(phone) && !TextUtils.isEmpty(phoneNumber)) {
                            phone = phoneNumber;
                        }
                        if (Contact.phoneDescription.containsKey(phoneClassification)) {
                            phoneDescription = Contact.phoneDescription.get(phoneClassification);
                        } else {
                            phoneDescription = Contact.DEFAULT_DESCRIPTION;
                        }

                        contact.addCommonContact(new CommonContact(phoneNumber, phoneClassification, CustomerConstant.CUSTOMER_CONTACT_TYPE_PHONE, phoneDescription));
                    } while (cursorPhones.moveToNext());
                }
                cursorPhones.close();
            }

            // 获取该联系人邮箱
            Cursor cursorEmails = context.getContentResolver().query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    new String[]{
                            ContactsContract.CommonDataKinds.Email.DATA,
                            ContactsContract.CommonDataKinds.Email.TYPE
                    },
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                            + " = " + name_raw_contact_id, null, null);

            if (cursorEmails != null) {
                if (cursorEmails.moveToFirst()) {
                    do {
                        // 遍历所有的邮箱
                        String emailValue = cursorEmails.getString(0);
                        if (TextUtils.isEmpty(emailValue) && !TextUtils.isEmpty(emailValue)) {
                            email = emailValue;
                        }
                        String emailClassification = cursorEmails.getString(1);

                        String emailDescription = null;
                        if (Contact.emailDescription.containsKey(emailClassification)) {
                            emailDescription = Contact.emailDescription.get(emailClassification);
                        } else {
                            emailDescription = Contact.DEFAULT_DESCRIPTION;
                        }
                        contact.addCommonContact(new CommonContact(emailValue, emailClassification, CustomerConstant.CUSTOMER_CONTACT_TYPE_EMAIL, emailDescription));
                    } while (cursorEmails.moveToNext());
                }
                cursorEmails.close();
            }

            Cursor cursorIMs = context.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI,
                    new String[]{
                            ContactsContract.CommonDataKinds.Im.DATA,     //data1
                            ContactsContract.CommonDataKinds.Im.PROTOCOL,//data5
                            ContactsContract.CommonDataKinds.Im.DATA6     //data6
                    },
                    ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
                            + Im.CONTENT_ITEM_TYPE + "'",
                    new String[]{name_raw_contact_id}, null);

            if (cursorIMs != null) {
                if (cursorIMs.moveToFirst()) {
                    do {
                        // 遍历所有的电话号码
                        String imValue = cursorIMs.getString(0);
                        String imClassification = cursorIMs.getString(1);
                        String imDescription = null;
                        if ("-1".equals(imClassification)) {//自定义的im，如yahoo等
                            imDescription = cursorIMs.getString(2);
                        } else {//预置的im
                            if (Contact.imDescription.containsKey(imClassification)) {
                                imDescription = Contact.imDescription.get(imClassification);
                            } else {
                                imDescription = Contact.DEFAULT_DESCRIPTION;//"其它";
                            }
                        }
                        contact.addCommonContact(new CommonContact(imValue, imClassification, CustomerConstant.CUSTOMER_CONTACT_TYPE_IM, imDescription));
                    } while (cursorIMs.moveToNext());
                }
                cursorIMs.close();
            }

            if (CustomerConstant.CustomerImportMode.FOR_NET) {
                List<CustomerContact> list = new ArrayList<>();
                setCustomerContact(list, CustomerConstant.CustomerContact.TYPE_PHONE, phone);
                setCustomerContact(list, CustomerConstant.CustomerContact.TYPE_EMAIL, email);
                cd.setListCustomerContact(list);
                if (!TextUtils.isEmpty(cd.getNamePrefix())) {
                    customerDetails.add(cd);
                }
            }

            StringBuffer sql_insert_customer_contact = new StringBuffer();
            sql_insert_customer_contact.append("INSERT INTO " + CustomerConstant.TABLE_CUSTOMER_CONTACT + "("
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_UUID + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_CTYPE + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_CVALUE + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_CLASSIFICATION + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_DESCRIPTION + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_CUSTOMERUUID + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_CHANGESTATUS + ","
                    + CustomerConstant.COLUMN_CUSTOMER_CONTACT_ISDEFAULT + ")");
            sql_insert_customer_contact.append(" VALUES( ?, ?, ?, ?, ?, ?, ?, ?)");

            SQLiteStatement statement_customer_contact = db.compileStatement(sql_insert_customer_contact.toString());
            db.beginTransaction();
            try {
                if (contact.commonContacts != null) {
                    for (CommonContact commonContact : contact.commonContacts) {
                        String uuid_customer_contact = UUID.randomUUID().toString();
                        statement_customer_contact.bindString(1, uuid_customer_contact);
                        statement_customer_contact.bindLong(2, commonContact.type);
                        statement_customer_contact.bindString(3, commonContact.value);
                        statement_customer_contact.bindLong(4, Integer.valueOf(commonContact.classification));
                        statement_customer_contact.bindString(5, commonContact.description);
                        statement_customer_contact.bindString(6, contact.customerUuid);
                        statement_customer_contact.bindLong(7, CustomerConstant.COLUMN_CHANGE_STATUS_ADD);
                        statement_customer_contact.bindLong(8, 0);
                        statement_customer_contact.executeInsert();
                    }
                }
                db.setTransactionSuccessful();
            } catch (Exception e) {
                Log.d(TAG, "===============insert to db exception ! e is " + e.getMessage());
                taskState = TASK_STATE_FAIL;
                e.printStackTrace();
            } finally {
                db.endTransaction();
            }
        }
        dbManager.close();
        if (!CustomerConstant.CustomerImportMode.FOR_NET) {
            setStateDone();
        } else {
            createBatchCustomer(customerDetails, contacts);
        }
    }

    private void setCustomerContact(List<CustomerContact> list, int type, String value) {
        CustomerContact cc = new CustomerContact();
        cc.ctype = type;
        cc.cvalue = value;
        list.add(cc);
    }


    private void createBatchCustomer(List<CustomerDetail> customerDetails, ArrayList<Contact> contacts) {
        JsonUtil.parseObjectToJsonWithTagAndPrefix("create batch customerDetails ====> ", customerDetails);
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.createBatchCustomer(customerDetails).subscribe(getCustomerCUSubscriber(contacts));
    }

    private Observer<CustomerCRUDRetJson> getCustomerCUSubscriber(ArrayList<Contact> contacts) {
        return new Observer<CustomerCRUDRetJson>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CustomerCRUDRetJson customerCreateRetJson) {
                if (customerCreateRetJson == null) {
                    setStateDone();
                    dismissDialog();
                    return;
                }
                if (customerCreateRetJson.error != null) {
                    ToastUtil.showToast("客户批量创建失败 \n" + "出错代码为:"
                            + customerCreateRetJson.error.message);
                    setStateDone();
                    dismissDialog();
                    return;
                }
                if (customerCreateRetJson.error == null) {
                    if (customerCreateRetJson.data == null) {
                        setStateDone();
                        dismissDialog();
                        return;
                    } else {
                        setStateDone();
                        insertDataToCustomerFromContactTable(contacts, customerCreateRetJson.data.customerBatch);
                        refreshMainList();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast("客户批量创建失败" + e.getMessage());
                dismissDialog();
                setStateDone();
            }

            @Override
            public void onComplete() {

            }
        };
    }

    private void insertDataToCustomerFromContactTable(ArrayList<Contact> contacts, List<CustomerCRUDRetJson.CustomerBatch> customerBatch) {
        if (contacts == null || contacts.size() == 0) {
            return;
        }
        if (customerBatch == null || customerBatch.size() == 0) {
            return;
        }

        HashMap<String, String> remarkAndRetCUuid = new HashMap<>();
        for (CustomerCRUDRetJson.CustomerBatch item : customerBatch) {
            if (TextUtils.isEmpty(item.importContact)) {
                continue;
            }
            remarkAndRetCUuid.put(item.importContact, item.customerId);
        }

        new Thread() {
            @Override
            public void run() {
                ArrayList<Contact> contactsWithRemarkUuid = contacts;
                int identity = CustomerData.getCurrentUserIdentity();

                StringBuffer sql_insert_customer_from_contact_for_import = new StringBuffer();
                sql_insert_customer_from_contact_for_import.append("INSERT INTO " + CustomerConstant.CustomerFromContact.TABLE_NAME + "("
                        + CustomerConstant.CustomerFromContact.UUID + ","
                        + CustomerConstant.CustomerFromContact.CUSTOMER_NAME + ","
                        + CustomerConstant.CustomerFromContact.CUSTOMER_UUID + ","
                        + CustomerConstant.CustomerFromContact.CONTACT_NAME + ","
                        + CustomerConstant.CustomerFromContact.CONTACT_RAW_ID + ","
                        + CustomerConstant.CustomerFromContact.CONTACT_SORT_KEY + ","
                        + CustomerConstant.CustomerFromContact.CHANGE_STATUES + ","
                        + CustomerConstant.CustomerFromContact.IDENTITY + ")");
                sql_insert_customer_from_contact_for_import.append(" VALUES( ?, ?, ?, ?, ?, ?, ?, ?)");

                DatabaseManager dbManager = DatabaseManager.getInstance(AppContext.getInstance().getApplicationContext());
                dbManager.open();
                SQLiteDatabase db = dbManager.getSqliteDatabase();
                SQLiteStatement statement_customer_from_contact_for_import = db.compileStatement(sql_insert_customer_from_contact_for_import.toString());
                db.beginTransaction();

                try {
                    int size = contactsWithRemarkUuid.size();
                    for (int i = 0; i < size; i++) {
                        Contact contact = contactsWithRemarkUuid.get(i);
                        if (contact.remarkUuid == null) {
                            continue;
                        }
                        String realCustomerUuid = remarkAndRetCUuid.get(contact.remarkUuid);
                        if (realCustomerUuid == null) {
                            continue;
                        }

                        //1.往customer_from_contact表中添加一条数据
                        statement_customer_from_contact_for_import.bindString(1, UUID.randomUUID().toString());//UUID
                        statement_customer_from_contact_for_import.bindString(2, contact.name);//CUSTOMER_NAME
                        statement_customer_from_contact_for_import.bindString(3, realCustomerUuid);//CUSTOMER_UUID
                        statement_customer_from_contact_for_import.bindString(4, contact.name);
                        statement_customer_from_contact_for_import.bindString(5, contact.rawContactId);
                        statement_customer_from_contact_for_import.bindString(6, contact.sortKeyString);
                        statement_customer_from_contact_for_import.bindLong(7, CustomerConstant.COLUMN_CHANGE_STATUS_ADD);
                        statement_customer_from_contact_for_import.bindLong(8, identity);
                        statement_customer_from_contact_for_import.executeInsert();
                    }
                    db.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    db.endTransaction();
                }
                dbManager.close();
            }
        }.start();
    }

    private void refreshMainList() {
        EventBus.getDefault().post(new EventCustomerListRefresh());
    }

    private void dismissDialog() {
        EventBus.getDefault().post(new MaterialishProgressDialog.MaterialishProgressDialogEvent(false));
    }

    public void setContactsWithCUuid(ArrayList<Contact> contactsWithCUuid) {
        this.contactsWithCUuid = contactsWithCUuid;
    }

    private void setStateDone() {
        if (taskState != TASK_STATE_FAIL) {
            taskState = TASK_STATE_DONE;
        }
    }

}
